/**
 * Created by apple on 2018/2/23.
 */
try{
    if (socket) {
        socket.close();
    }

    if(!localStorage.getItem('content')){
        location.href = document.getElementsByTagName("base")[0].getAttribute("href") + 'login/login.html';
    }

    //var socket = new WebSocket("ws://192.168.1.5:8080/ks_manager/webSocket?systemCode=" + JSON.parse(localStorage.getItem('content')).admin.systemcode);
    var socket = new WebSocket("ws://192.168.1.149:8080/ks_manager/webSocket/" + JSON.parse(localStorage.getItem('content')).admin.systemcode + "/0");

    socket.onopen = function (e) {
        console.log('链接！');
    }

    socket.onmessage = function (e) {
        console.log(e.data);
        if (e.data === 'logout') {
            socket.close();
            $(".logOut_winBox").show();
            //alert("你的账号已在别处登录！")
            //localStorage.clear();
            //location.href = 'login/login.html';
        }
    }

    $('#sureLogOut').on("click", function () {
        location.href = document.getElementsByTagName("base")[0].getAttribute("href") + 'login/login.html';
    })
}catch (e){
    throw e;
}

requireJS(['constant', 'site', 'handlebars'], function (constant, site, Handlebars) {
    constant.initHandlebars(Handlebars)
    var refreshHead = function () {
        //decodeURIComponent(location.search);
        //获取服务端返回的content,渲染顶部菜单
        var content = JSON.parse(localStorage.getItem('content'));
        //渲染顶部
        var navTpl = Handlebars.compile($("#nav-center-tpl").html());
        $('.nav-center').html(navTpl(content));

        //渲染右侧登录信息
        var navRightTpl = Handlebars.compile($("#nav-right-tpl").html());
        $('.nav-right').html(navRightTpl(content));

        //获取url中的h参数，h表示head头部选中哪个菜单，设置菜单激活
        var menuIndex = constant.getAurlparam('h') || 0;
        $($('#nav-parent').children()[menuIndex]).addClass("actives");

        //渲染左侧菜单激活
        var leftIndex = constant.getAurlparam('i') || 0;

        //渲染三级菜单激活
        var thirdMenusIndex = constant.getAurlparam('t') || 0;

        //渲染左侧菜单
        if (menuIndex == 'special') {
            var sideMenus = [{
                url: 'informa/admin_informa.html',
                name: '个人信息',
                desciption: '',
                children: [{
                    name: '个人信息',
                    url: 'informa/admin_informa.html'
                }]
            }, {
                url: 'informa/mylims.html',
                name: '我的权限',
                children: [{
                    name: '我的权限',
                    url: 'informa/mylims.html'
                }]
            }, {
                url: 'informa/change_psw.html',
                name: '修改密码',
                children: [{
                    name: '修改密码',
                    url: 'informa/change_psw.html'
                }]
            }];
            var sideMenusTpl = Handlebars.compile($('#temleft-container-tpl').html());
            $('#temleft-container').html(sideMenusTpl(sideMenus));
            $($('#temleft-container > ul').children()[leftIndex]).addClass("light");

            var thirdMenus = {
                firstMenus: {
                    name: '个人中心'
                },
                secondMenus: sideMenus[leftIndex],
                thirdMenus: sideMenus[leftIndex].children[thirdMenusIndex],
                thirdMenusList: sideMenus[leftIndex].children
            }
            var thirdMenusTpl = Handlebars.compile($('#thirdMenus-container-tpl').html());
            $('#thirdMenus-container').html(thirdMenusTpl(thirdMenus));

            $('#thirdMenus-container .public-List').eq(thirdMenusIndex).addClass("publicListHover");
        }
        else {
            if (content.menus[menuIndex]) {
                var sideMenus = content.menus[menuIndex].children;
                var sideMenusTpl = Handlebars.compile($('#temleft-container-tpl').html());
                $('#temleft-container').html(sideMenusTpl(sideMenus));
                $($('#temleft-container > ul').children()[leftIndex]).addClass("light");
            }
            //渲染三级菜单
            if (content.menus[menuIndex].children[leftIndex]) {
                var thirdMenus = {
                    firstMenus: content.menus[menuIndex],
                    secondMenus: content.menus[menuIndex].children[leftIndex],
                    thirdMenus: content.menus[menuIndex].children[leftIndex].children[thirdMenusIndex],
                    thirdMenusList: content.menus[menuIndex].children[leftIndex].children
                }
                var thirdMenusTpl = Handlebars.compile($('#thirdMenus-container-tpl').html());
                $('#thirdMenus-container').html(thirdMenusTpl(thirdMenus));

                $('#thirdMenus-container .public-List').eq(thirdMenusIndex).addClass("publicListHover");
            }
        }


        // $('#nav-parent > li:last-child').hide();//顶部最后一个菜单（后台首页）隐藏

        //顶部菜单点击事件,h顶部栏高亮
        $('#nav-parent > li').on('click', function () {
            var $this = $(this);
            var index = $this.index();
            var url = $this.data('url');//loanBefore%2forder.html%3froleId%3d6%26h%3d1%26i%3d3%26t%3d0
            //转码

            if (index != menuIndex) {
                if (url) {
                    //获取url中的h参数，h表示head头部选中哪个菜单，设置菜单激活
                    var menuIndex = index;
                    $($('#nav-parent').children()[menuIndex]).addClass("actives");


                    //获取三级菜单第一个栏的url
                    if (content.menus[menuIndex].children[0].children[0]) {
                        var thirdMenus = content.menus[menuIndex].children[0].children[0].url;
                        if (thirdMenus) {
                            url = thirdMenus;
                        }
                    } else {
                        var sideMenus = content.menus[menuIndex].children[0].url;
                        if (sideMenus) {
                            url = sideMenus;
                        }
                    }



                    if (url.indexOf("?") > -1) {
                        url += ("&h=" + index + "&i=" + 0 + "&t=" + 0);
                    }
                    else {
                        url += ("?h=" + index + "&i=" + 0 + "&t=" + 0);
                    }
                    pjaxGo(url);
                }
            }
        });


        $('#personalCenter').on('click', function () {
            pjaxGo('informa/admin_informa.html?h=special');
        })


        //左侧菜单点击事件
        $('#temleft > li').each(function (i, e) {
            var $this = $(this);
            var ii = i;
            $this.on('click', function () {
                if (ii != leftIndex) {
                    $this.siblings('li').removeClass('light');
                    $this.addClass('light');
                    var url = $this.data('url');
                    if (url) {
                        var leftIndex = ii;
                        // 判断有无三级菜单
                        if (menuIndex != 'special') {
                            var is_no = content.menus[menuIndex].children[leftIndex].children[0];
                            if (is_no) {
                                //获取三级菜单第一个栏的url
                                var thirdMenus = content.menus[menuIndex].children[leftIndex].children[0].url;
                            }
                            if (thirdMenus) {
                                url = thirdMenus;
                            }
                        }
                        if (url.indexOf("?") > -1) {
                            url += ("&h=" + menuIndex + "&i=" + ii + "&t=" + 0);
                        }
                        else {
                            url += ("?h=" + menuIndex + "&i=" + ii + "&t=" + 0);
                        }
                        /*url = constant.getBefore(url) + '?' + encodeURIComponent(constant.getCaption(url));*/
                        pjaxGo(url);
                    }
                }
            });
        });

        //三级菜单点击事件
        $('#thirdMenus-container .public-List').each(function (i, e) {
            var $this = $(this);
            var ii = i;
            $this.on('click', function () {
                if (ii != thirdMenusIndex) {
                    $this.siblings('.public-List').removeClass('publicListHover');
                    $this.addClass('publicListHover');
                    if (content.menus[menuIndex].children[leftIndex].children[ii].key == 'allCustomer') {
                        $.each(content.menus, function (firstI, first) {
                            $.each(first.children, function (secondI, second) {
                                $.each(second.children, function (thirdI, third) {
                                    if (third.key == 'allCustomer') {
                                        menuIndex = firstI;
                                        leftIndex = secondI;
                                        ii = thirdI;
                                    }
                                })
                            })
                        })
                    }
                    var url = $this.data('url');
                    if (url) {

                        if (url.indexOf("?") > -1) {
                            url += ("&h=" + menuIndex + "&i=" + leftIndex + "&t=" + ii);
                        }
                        else {
                            url += ("?h=" + menuIndex + "&i=" + leftIndex + "&t=" + ii);
                        }
                        console.log(encodeURIComponent(constant.getCaption(url)));
                        console.log(constant.getBefore(url))
                        /*url = constant.getBefore(url) + '?' + encodeURIComponent(constant.getCaption(url));*/
                        pjaxGo(url);
                    }
                }
            });
        });
    }

    refreshHead();

    $(document).on('pjax:end', function () {//pjax结束刷新一遍左侧和头部
        refreshHead();
    });


    //全选功能
    $("input[name='ch_id_all']").on('click', function () {
        var _checked = $("input[name='ch_id']")
        if ($(this).prop('checked')) {
            _checked.prop('checked', true)
        }
        else {
            _checked.prop('checked', false)
        }
    })

//日期控件初始化
    $(".datepicker").datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        pickerPosition: 'bottom',
    })


    $("#exitLogin").on("click", function () {
        window.location.href = document.getElementsByTagName("base")[0].getAttribute("href") + "login/login.html"
        socket.close();
    })

    /*$("#loading").mLoading({
        //text:"",//加载文字，默认值：加载中...
        icon: "static/images/loading.gif",//加载图标，默认值：一个小型的base64的gif图片
        html: false,//设置加载内容是否是html格式，默认值是false
        content: "",//忽略icon和text的值，直接在加载框中显示此值
        mask: false//是否显示遮罩效果，默认显示
    });*/
//设置title
    site.send({
        url: 'manager/queryCarloanService.do',
        async: false,
        data: {},
        callback: function (data) {
            var list = JSON.parse(data);
            document.title = list.content.bg_name;
        }
    })
});

var _onTitlebarMouseDown = function (event, el) {
    var uiUtils = baidu.editor.ui.uiUtils;
    var domUtils = baidu.editor.dom.domUtils;
    var rect;
    var me = this;
    var dialogId = el.getAttribute('id');//'image_upload_pop';

    var safeSetOffset = function (offset) {
        // var me = this;
        var el = getDom();
        var vpRect = uiUtils.getViewportRect();
        var rect = uiUtils.getClientRect(el);
        var left = offset.left;
        if (left + rect.width > vpRect.right) {
            left = vpRect.right - rect.width;
        }
        var top = offset.top;
        if (top + rect.height > vpRect.bottom) {
            top = vpRect.bottom - rect.height;
        }
        el.style.left = Math.max(left, 0) + 'px';
        el.style.top = Math.max(top, 0) + 'px';
    }
    var getDom = function (name) {
        if (!name) {
            return document.getElementById(dialogId);
        } else {
            return document.getElementById(dialogId + '_' + name);
        }
    };

    uiUtils.startDrag(event, {
        ondragstart: function () {
            rect = uiUtils.getClientRect(getDom());
            // me.getDom('contmask').style.visibility = 'visible';
            // me.dragMask.show(me.getDom().style.zIndex - 1);
        },
        ondragmove: function (x, y) {
            var left = rect.left + x;
            var top = rect.top + y;
            safeSetOffset({
                left: left,
                top: top
            });
        },
        ondragstop: function () {
            // me.getDom('contmask').style.visibility = 'hidden';
            // domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
            // me.dragMask.hide();
        }
    });

};



